<template>
  <view class="perfect-info">
    <view class="avatar-wrap">
      <image class="avatar-wrap-avatar" :src="avatarInfo.avatar" />
      <view class="extra-wrap" @tap="handleChangeAvatar">
        <text class="extra-wrap-desc"
          >更换{{ isDefaultAvatar ? "默认" : "" }}头像</text
        >
        <view class="extra-wrap-icon"></view>
      </view>
    </view>
    <view class="info-item">
      <view class="info-item-title">姓名</view>
      <input
        class="info-item-inpcontent"
        :maxlength="10"
        v-model="name"
        @input="handleGetNameInpValue"
        :focus="isInpFocusState"
        @focus="handleInpOperate('FOCUS')"
        @blur="handleInpOperate('BLUR')"
        placeholder="请输入姓名"
      />
      <image
        v-if="isShowClearBtn"
        @tap="handleClearName"
        class="info-item-icon"
        src="@/assets/icon/clear-btn.png"
      />
    </view>
    <view class="info-item" style="flex:1;">
      <view class="info-item-title">性别</view>
      <picker
        mode="selector"
        :range="selector"
        :value="gender"
        @change="handleSexChange"
        @cancel="handleCancel"
      >
        <view class="info-item-content">
          <view v-if="!selector[gender]" class="content-desc">请输入性别</view>
          <view v-else class="content-title">
            {{ selector[gender] }}
          </view>
          <view class="info-item-icon"></view>
        </view>
      </picker>
    </view>
    <view class="info-item">
      <view class="info-item-title">年级</view
      ><view class="info-item-content" @tap="handleShowModal('GRADE')">
        <view v-if="!gradeInfo.id" class="content-desc">请输入年级</view>
        <view v-else class="content-title">
          {{ gradeInfo.title }}
        </view>
        <view class="info-item-icon"></view>
      </view>
    </view>
    <view class="info-city-desc" :class="gradeBottomExtraDescClass"
      >（每年7月1日系统自动升年级）</view
    >
    <view class="info-item">
      <view class="info-item-title">城市</view
      ><view class="info-item-content" @tap="handleShowModal('CITY')">
        <view v-if="!cityInfo.title" class="content-desc">请输入城市</view>
        <view v-else class="content-title">
          {{ cityInfo.title }}
        </view>
        <view class="info-item-icon"></view>
      </view>
    </view>
    <!-- 按钮 -->
    <view class="perfect-info-footer">
      <view
        v-if="isLogonPage"
        class="perfect-info-footer__desc"
        @tap="handleToAgrermentPage"
        >登录/注册即代表已阅读并同意<text data-id="USER">《用户协议》</text
        ><text data-id="PRIVACY">《隐私协议》</text></view
      >
      <finish-button
        width="100%"
        :disabled="isPerfectSubmitInfo"
        @click="handleSubmitInfo"
        >完成</finish-button
      >
    </view>
    <at-toast
      :isOpened="is_opened"
      :text="toastText"
      :onClose="handleCloseToast"
    ></at-toast>
    <actionSheet
      :isOpenedModal.sync="isOpenedModal"
      :isShowTitle="true"
      :modalTitle="actionSheetInfo.title"
      :height="actionSheetInfo.height"
    >
      <gradeModal
        v-if="isShowGradeModal && isOpenedModal"
        :isOpenedModal="isOpenedModal"
        :gradeInfo="gradeInfo"
        :gradeOptions="gradeOptions"
        @modalClose="handleCloseGradeModal"
        @getGrade="handleGetGrade"
      >
      </gradeModal>
      <cityModal
        v-if="!isShowGradeModal && isOpenedModal"
        :cityInfo="cityInfo"
        :cityList="cityList"
        @changeCity="handleChange"
      />
    </actionSheet>
    <!-- 选择城市弹窗确认 -->
    <at-modal
      class="custom-confirm"
      :closeOnClickOverlay="false"
      :isOpened="isShowConfirm"
      :onClose="handleModalCancel"
      :onCancel="handleModalCancel"
      ><AtModalContent>您选择的城市为：{{ midCityInfo.title }} </AtModalContent>
      <AtModalAction>
        <view class="modal-footer" @tap="handleModalOperate">
          <text data-key="cancel">取消</text>
          <text data-key="ok">确定</text>
        </view>
      </AtModalAction>
    </at-modal>
  </view>
</template>

<script>
import Taro from "@tarojs/taro";
import actionSheet from "@/components/action-sheet/index";
import gradeModal from "@/pages/login-perfect/perfect-info/grade-modal/index";
import cityModal from "@/pages/login-perfect/perfect-info/city-modal/index";
import finishButton from "@/components/finish-button/index";
import { debounce } from "@/libs/util";
import { AtModalAction, AtModalContent } from "taro-ui-vue";
import { getUserInfo } from "@/libs/api/login";
import {
  getLearnSectionGrades,
  getAvatarByGender,
  getLetterSortCitys
} from "@/libs/api/base-api";
/**中英文、数字正则 */
const NAME_REG = /[^\u4E00-\u9FA5a-zA-Z\d]/g;
const MEN = 1;
const WOMEN = 2;

const GENDER = {
  0: MEN,
  1: WOMEN
};
export default {
  name: "PerfectInfo",
  props: {
    formWhere: {
      type: String,
      default: "LOGON"
    },
    /**头像信息 */
    avatarInfo: {
      type: Object,
      default: () => {
        return {};
      }
    },
    /**学生信息 */
    student: {
      type: Object,
      default: () => {
        return {};
      }
    },
    ok: {
      type: Function,
      default: () => {}
    }
  },
  components: {
    actionSheet,
    gradeModal,
    cityModal,
    finishButton,
    AtModalAction,
    AtModalContent
  },
  data() {
    return {
      isInpFocusState: false,
      isDefaultAvatar: true,
      isShowConfirm: false,
      isOpenedModal: false,
      selector: ["男", "女"],
      gender: undefined,
      name: "",
      gradeInfo: {},
      isNameFocused: false,
      age: 10,
      currentModal: undefined,
      midCityInfo: {},
      gradeOptions: [],
      cityInfo: {},
      cityList: []
    };
  },
  computed: {
    /**是否显示清除按钮 */
    isShowClearBtn() {
      return this.isNameFocused && this.name;
    },
    /**是否展示年级弹窗 */
    isShowGradeModal() {
      return this.currentModal === "GRADE";
    },
    /**弹窗标题信息 */
    actionSheetInfo() {
      const title = `请选择${this.isShowGradeModal ? "年级" : "城市"}`;
      const height = this.isShowGradeModal ? 960 : 932;
      return { title, height };
    },
    /**是否为登录注册页 */
    isLogonPage() {
      return this.formWhere === "LOGON";
    },
    gradeBottomExtraDescClass() {
      return {
        "add-baby-desc": !this.isLogonPage
      };
    },
    submitInfo() {
      return {
        city_id: this.cityInfo.id,
        grade_id: this.gradeInfo.id,
        gender: GENDER[this.gender],
        name: this.name
      };
    },
    isPerfectSubmitInfo() {
      return Object.values(this.submitInfo).some(i => !Boolean(i));
    }
  },
  watch: {
    student(newVal) {
      this.handleInitData();
    }
  },
  created() {
    this.handleGetGradeList();
    this.handleGetCityList();
  },
  methods: {
    async handleGetCityList() {
      const { data } = await getLetterSortCitys();
      this.cityList = data;
      console.log(data, "data");
      // this.list = data;
    },
    handleInitData() {
      const {
        gender,
        name,
        offline_grade = {},
        city_id,
        city_name,
        base_districts_province_id
      } = this.student;
      if (this.student.offline_grade) {
        let { grade_id, grade_name } = offline_grade;
        this.gradeInfo = { id: grade_id, title: grade_name };
      }
      if (city_id) {
        this.cityInfo = {
          id: city_id,
          title: city_name,
          base_districts_province_id
        };
      }
      /**格式化性别 */
      this.gender = gender - 1;
      this.name = name;
    },
    handleChangeAvatar() {
      const timer = this.isInpFocusState ? 600 : 0;
      setTimeout(() => {
        Taro.navigateTo({
          url: `/pages/mine/edit-avatar/index?info=${JSON.stringify(
            this.avatarInfo
          )}`,
          success: () => {
            Taro.eventCenter.once("handleGetAvatar", data => {
              this.isDefaultAvatar = false;
              this.$emit("change-avatar", data);
            });
          }
        });
      }, timer);
    },
    /**获取年级等级列表 */
    async handleGetGradeList() {
      const { data } = await getLearnSectionGrades();
      this.gradeOptions = data;
      console.log(data);
    },
    /**选择城市弹窗按钮操作 */
    handleModalOperate({
      target: {
        dataset: { key }
      }
    }) {
      let strategy = {};
      strategy["cancel"] = this.handleModalCancel;
      strategy["ok"] = () => {
        this.cityInfo = this.midCityInfo;
        this.handleModalCancel();
        this.isOpenedModal = false;
      };
      strategy[key] && strategy[key]();
    },
    /**选择城市 */
    handleChange(value) {
      this.isShowConfirm = true;
      this.midCityInfo = value;
    },
    /**关闭城市确定弹窗 */
    handleModalCancel() {
      this.isShowConfirm = false;
    },
    /**打开弹窗 */
    handleShowModal(type) {
      this.currentModal = type;
      this.isOpenedModal = true;
    },
    handleGetGrade(grade) {
      this.gradeInfo = grade;
    },
    handleCloseGradeModal() {
      this.isOpenedModal = false;
      this.currentModal = undefined;
    },
    /**提交信息 */
    handleSubmitInfo() {
      const query = Object.assign(
        {
          base_districts_province_id: this.cityInfo.base_districts_province_id
        },
        this.submitInfo
      );
      this.ok(query);
    },
    /**跳转协议 */
    handleToAgrermentPage({
      target: {
        dataset: { id }
      }
    }) {
      if (!id) return;
      Taro.navigateTo({
        url: `/pages/login-perfect/about-agreement/index?id=${id}`
      });
    },
    async handleSexChange({ detail: { value } }) {
      this.gender = value;
      if (this.isDefaultAvatar) {
        const { data } = await getAvatarByGender({
          gender: GENDER[value]
        }).catch(({ message }) => {
          this.$message(message);
        });
        this.$emit("change-avatar", data);
      }
    },
    handleCancel() {},
    /**清除姓名输入 */
    handleClearName() {
      this.name = "";
    },
    /**姓名输入的特殊处理 */
    handleGetNameInpValue: debounce(function({ detail: { value } }) {
      if (value.match(NAME_REG)?.length) {
        this.$message("姓名仅支持汉字、字母和数字");
      }

      /**只能输入中英文、数字 */
      this.name = value.replace(NAME_REG, "");
    }),
    handleInpOperate(type) {
      const isFocus = type === "FOCUS";
      this.isInpFocusState = isFocus;
      if (isFocus) return (this.isNameFocused = true);
      if (!this.name) this.isNameFocused = false;
    }
  }
};
</script>

<style lang="scss">
.perfect-info {
  font-size: 32px;
  %base-height {
    box-sizing: border-box;
    border-bottom: 2px solid #f3f3f3;
    height: 120px;
    display: flex;
  }
  %base-icon {
    width: 44px;
    height: 44px;
    background: url("~@/assets/icon/right.png");
    background-size: 44px;
  }
  .avatar-wrap {
    padding: 38px 30px 22px;
    @extend %base-height;
    height: 108px;
    display: flex;
    align-items: center;
    box-sizing: content-box;
    &-avatar {
      border-radius: 50%;
      width: 108px;
      height: 108px;
      margin-right: 40px;
    }
    .extra-wrap {
      height: 44px;
      flex: 1;
      display: flex;
      align-items: center;
      &-desc {
        flex: 1;
        color: #909399;
      }
      &-icon {
        @extend %base-icon;
      }
    }
  }
  .perfect-title {
    padding: 26px 30px 0;
    @extend %base-height;
    height: 158px;
    &-desc {
      flex: 1;
      margin-top: 36px;
      color: #909399;
      line-height: 44px;
    }
    &-icon {
      @extend %base-icon;
    }
  }
  .info-item {
    @extend %base-height;
    padding: 32px 30px 0;
    &-title {
      line-height: 44px;
      width: 168px;
      color: #606266;
    }
    &-inpcontent {
      flex: 1;
      color: #303133;
      line-height: 44px;
      height: 44px;
      caret-color: #ffad1c;
    }
    picker {
      flex: 1;
    }
    .info-item-content {
      width: 100%;
      display: flex;

      .content-desc {
        flex: 1;
        color: #c0c4cc;
      }

      .content-title {
        flex: 1;
        color: #303133;
      }
    }
    &-content {
      flex: 1;
      color: #c0c4cc;
      line-height: 44px;
      height: 44px;
    }
    .input-placeholder {
      color: #c0c4cc;
    }

    &-icon {
      width: 44px;
      height: 44px;
      background: url("~@/assets/icon/right.png");
      background-size: 44px;
    }
  }
  .info-city-desc {
    height: 34px;
    font-size: 24px;
    font-weight: 400;
    line-height: 34px;
    color: #ff8000;
    opacity: 1;
    margin: 8px 0 16px 16px;
  }
  .add-baby-desc {
    color: #a13d0f;
  }
  &-footer {
    box-sizing: border-box;
    width: 100%;
    position: fixed;
    bottom: 16px;
    left: 0;
    padding: 0 30px;
    &__desc {
      font-size: 24px;
      line-height: 34px;
      padding-left: 40px;
      margin-bottom: 28px;
      text {
        color: #ff8000;
      }
    }
    .finish-button {
      margin: 0 auto;
    }
  }
  .custom-comtainer-wrap {
    padding: 24px 30px 0;
  }
}
</style>
